<template>
  <div class="login-container">
    <el-card class="login-card"
             shadow="hover">
      <h2>登录</h2>
      <el-form ref="loginForm"
               :model="loginUserForm"
               :rules="rules"
               label-width="80px">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="loginUserForm.username"
                    placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="loginUserForm.password"
                    type="password"
                    placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="login">登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import Cookie from "js-cookie";
import {getMenu} from "@/api";

export default {
  data() {
    return {
      loginUserForm: {
        username: 'admin',
        password: 'admin'
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    login() {

      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // 在这里处理登录逻辑，例如向服务器发送登录请求等
          getMenu(this.loginUserForm).then(({data}) => {

            const {token,menuData} = data.data
            //设置token
            Cookie.set('token', token)
            if (data.code===20000) {
              this.$store.commit('setMenuData',menuData)
              //动态添加路由
              this.$store.commit('addMenu',this.$router)
              // 假设登录成功，跳转到首页或其他页面
              this.$message.success('登录成功！')
              this.$router.push('/home')
            }else{
              this.$message.error('登录失败,用户名或密码错误！')
            }
          }).catch(err => {
            console.log(err)
          })


          // 清空输入框
          // this.loginUserForm.username = '';
          // this.loginUserForm.password = '';
        }
      });
    }
  }
}
</script>

<style scoped
       lang="less">
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;

  .login-card {
    width: 400px;
    padding: 20px;


    h2 {
      text-align: center;
      margin-bottom: 20px;
    }
  }

}


</style>
